package utils;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import srw.Property;

/**
 *  Reads properties tree from file
 *	@see Property
 */

public class TreeUtils {

	public static Property readTree(String path) {
		
		System.err.println("BUILD PROPERTIES TREE");
		try {
			BufferedReader bufr = new BufferedReader(new FileReader(path));
			addNode(new LinesReader(bufr), null, 0);
			bufr.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	private static void addNode(LinesReader reader, Property parent, int curDepth) throws IOException {
		
		Property lastAdded = null;
		
		while(true) {
			String line = reader.readLine();
			if (line == null) 
				return;

			int depth = 0;
			while (line.startsWith(" ", depth))
				depth++;

			if (depth == curDepth) {
				lastAdded = Property.createNew(line.trim());
				lastAdded.setParent(parent);
			} else if (depth > curDepth) {
				reader.pushBack();
				addNode(reader, lastAdded, depth);
			} else {
				reader.pushBack();
				return;
			}
		}
	}
	
}
